<script lang="ts">
import { useAntdForm } from '@peng_kai/kit/antd';
import { InputPassword } from '~comp/input';
import { InputOtp } from '~/components/input';
import cs from '~/composables/useCS';
import { flzxsqc } from '~/utils';

export const enable2FAPopup = useAntdModal(
  // eslint-disable-next-line import/no-self-import
  defineAsyncComponent(() => import('./Enable2FA.vue')),
  {
    title: computed(() => $t('afNAw86zd2Lbvw8CpjGmz')),
    wrapClassName: 'ant-cover__Modal-drawer __screen-drawer',
    rejectOnClose: true,
    maskClosable: false,
    width: 700,
    centered: true,
    footer: null,
  },
);
</script>

<script setup lang="ts">
const emits = defineEmits<{
  close: [];
  confirm: [];
}>();

const { userInfoQry } = useUserStore();
const form = useAntdForm({
  enable_authenticator: {
    value: 1,
  },
  security_code: {
    value: '',
    rules: [{ required: true, type: 'string', message: $t('9QtWqL7hc0fzViFGn0Es') }],
  },
  password: {
    value: '',
    rules: [{ required: true, type: 'string', message: $t('mfFbQx6d5lMlEhlQg5eV') }],
  },
}, {
  transform(state) {
    return { ...state, password: flzxsqc(state.password) };
  },
});
const codeQry = useQuery({
  queryKey: [apis.apiAuthenticatorQrCode.id],
  queryFn: () => apis.apiAuthenticatorQrCode(undefined),
  gcTime: 0,
});
const switch2faMut = useMutation({
  mutationKey: [apis.apiAuthenticatorSwitch.id],
  mutationFn: apis.apiAuthenticatorSwitch.setDefaultConfig({
    successMessage: $t('iunYy_42XbAoXfBtZq08a'),
  }),
  onSuccess() {
    userInfoQry.refetch();
    emits('confirm');
  },
});

const disabled = computed(() => false);
const url = computed(() => decodeURIComponent(decodeURIComponent(codeQry.data.value?.qr_code ?? '')));
const secretKey = computed(() => codeQry.data.value?.secret_key);
const savedKey = ref(false);

async function confirm() {
  switch2faMut.mutate({ requestBody: form.stateTF });
}
</script>

<template>
  <div>
    <!--  -->
    <I18nT keypath="b0y0d0rTkl5PyjbSfvUl6" tag="div">
      <template #link>
        <a class="!url-yellow-underline" href="https://support.google.com/accounts/answer/1066447" target="_blank">Google Authenticator</a>
      </template>
    </I18nT>
    <div class="mt-2">
      <RouterLink :to="{ name: RN.HELP_GOOGLE_AUTHENTICATOR }" class="!url-yellow-underline" @click="emits('close')">
        {{ $t('i6IoIo6niVcZva5RcI3zG') }}
      </RouterLink>
    </div>

    <!--  -->
    <div class="secret-key-wrapper my-5 rounded-2 bg-sys-layer-a p-4">
      <div class="mobilel:(col-span-full)">
        {{ $t('j16hRXpnSXaNsDve4Zzcb') }}
      </div>
      <div class="mx-auto my-4 h-50 w-50 rounded-2 bg-white p-3 op-90 mobilel:([grid-area:qrcode] m-0)">
        <AQrcode :value="url" color="#000" bgColor="#FFF" :size="400" :status="secretKey ? 'active' : 'loading'" />
      </div>
      <div v-if="secretKey" class="flex rounded-2 bg-sys-layer-d p-3" data-copy-title>
        <div class="line-clamp-1 flex-1 break-all">
          {{ secretKey }}
        </div>
        <TCopy class="flex-none" :source="secretKey" trigger="div[data-copy-title]" />
      </div>
      <div>
        <p><i class="i-local:warn mr-2 text-1.2em" />{{ $t('8Lg9mPoCVudUyUuuvKh0') }}</p>
        <p>{{ $t('fuPpRfl6lfq8Fl9X1y82b') }}</p>
      </div>
      <div>
        <ACheckbox v-model:checked="savedKey">
          <span class="text-sys-text-body">
            {{ $t('iJ0pD6j5PuIemMc5ehRwR') }}
          </span>
        </ACheckbox>
      </div>
    </div>

    <!--  -->
    <div class="mt-5">
      <AForm
        v-bind="form.props" class="ant-cover__Form-compact"
        hideRequiredMark :disabled="disabled" layout="vertical"
        @finish="confirm()"
      >
        <div class="mobilel:(flex gap-3)">
          <AFormItem v-bind="form.itemProps.password" class="flex-1" :label="$t('ph7eJFfBmsn7xFyvj8')">
            <InputPassword v-model:value="form.state.password" :placeholder="$t('sbNd6Np6qPuRup0ZhZbYz')" />
          </AFormItem>
          <AFormItem v-bind="form.itemProps.security_code" class="flex-1" :label="$t('vrOaTrsSDoDwKhZqxWG')">
            <InputOtp v-model:value="form.state.security_code" />
          </AFormItem>
        </div>

        <AButton
          class="ant-cover__Button-3d-primary mt-4" type="primary" htmlType="submit" block
          :disabled="disabled || !savedKey" :loading="switch2faMut.isPending.value"
        >
          {{ $t('fVhxPoy2u9I4Q6dqrMh') }}
        </AButton>
      </AForm>
    </div>

    <I18nT keypath="kcNEt0GGkp1fCQqf9S7K" tag="div" class="mt-3">
      <template #link>
        <a class="!url-yellow-underline" href="#" @click="cs.show">Live Chat</a>
      </template>
    </I18nT>
  </div>
</template>

<style lang="scss" scoped>
.secret-key-wrapper {
  display: grid;
  gap: 12px;

  @media bp-mobilel {
    align-items: start;
    align-content: flex-start;
    grid-template-areas:
      '. .'
      '. qrcode'
      '. qrcode'
      '. qrcode';
    grid-template-columns: 1fr auto;
    grid-template-rows: auto auto auto auto;
  }
}
</style>
